<template>
    <div class="cate">

        <el-card class="box-card">

            <!-- 按钮组 -->

            <div class="btn1">

                <el-button type="primary" @click="addVisible = true">新增</el-button>

                <el-button @click="plDel">删除</el-button>

            </div>

            <!-- 表格 -->
            <vxe-table size="small" border ref="xTree1" :column-config="{ resizable: true }"
                :tree-config="tableData.tableTreeConfig" :data="tableData.list1" :checkbox-config="{ highlight: true }"
                @checkbox-change="selectChangeEvent">
                <vxe-column type="checkbox" width="50" checkbox></vxe-column>
                <vxe-column field="name" title="分类名称" tree-node></vxe-column>
                <vxe-column field="img" title="图片">
                    <template #default="scope">
                        <el-image style="width: 25px; height: 20px" :zoom-rate="1.2" :src="scope.row.picture"
                            :preview-src-list="[scope.row.picture]" :initial-index="0" fit="cover" />
                    </template>
                </vxe-column>
                <vxe-table-column title="操作">
                    <template #default="scope">
                        <el-button size="small" link @click="handleEdit(scope.row)">
                            修改</el-button>
                        <el-button size="small" type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </vxe-table-column>
            </vxe-table>
            <!-- 分页 -->
            <vxe-pager style="margin-top:1rem" background v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize" :total="pagination.total" @page-change="handlePageChange"
                :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'FullJump']">
            </vxe-pager>

        </el-card>

        <!-- 新增记录对话框 -->
        <el-dialog v-model="addVisible" title="新增" width="30%" :before-close="handleClose">
            <el-form :model="form" label-width="260px" :rules="addrules" ref="addruleFormRef">
                <el-form-item label="图片" label-width="100px" prop="upload">
                    <el-upload class="avatar-uploader" :limit="1" action="http://127.0.0.1:3000/dev-api/api/uploadimg/"
                        ref="mYupload" :on-success="handleAvatarSuccess">
                        <img v-if="form.picture" :src="form.picture" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="分类名称" label-width="100px" prop="name">
                    <el-input v-model="form.name" placeholder="请填写" />
                </el-form-item>
                <el-form-item label="上级分类" label-width="100px" prop="options">
                    <el-cascader :options="tableData.option" :props="{ value: 'id', label: 'name', checkStrictly: true }"
                        v-model="form.pid" :show-all-levels="false" />
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleCancle(addruleFormRef)">取消</el-button>
                    <el-button type="primary" @click="onSubmit(addruleFormRef)">保存</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 修改记录对话框 -->
        <el-dialog v-model="editVisible" title="修改" width="30%" :before-close="handleEditClose">
            <el-form :model="Editform" label-width="260px" ref="Editform1" :rules="editrules">
                <el-form-item label="图片" label-width="100px">
                    <el-upload class="avatar-uploader" ref="EditFromimg"
                        action="http://127.0.0.1:3000/dev-api/api/uploadimg/" :on-success="handleAvatarSuccess1">
                        <img v-if="dist.picture" :src="dist.picture" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="分类名称" label-width="100px" prop="dist.name">
                    <el-input placeholder="请填写" v-model="dist.name" />
                </el-form-item>
                <el-form-item label="上级分类" label-width="100px">
                    <el-cascader :options="tableData.option" v-model="dist.pid"
                        :props="{ value: 'id', label: 'name', checkStrictly: true }" />
                </el-form-item>
                <el-form-item>
                    <el-button @click="reset(Editform1)">取消</el-button>
                    <el-button type="primary" @click="onEdit(Editform1)">修改</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { UploadProps } from 'element-plus'
import { VxeTableEvents, VxeTablePropTypes, VxeTableInstance, VxePagerEvents } from 'vxe-table'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import service from '@/utils/request'
import axios from 'axios'
// 分页
const pagination = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10
})
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    console.log(currentPage, pageSize);
    pagination.currentPage = currentPage
    pagination.pageSize = pageSize
    getData()
}

/***
 * 添加对话框
 * */
const addruleFormRef = ref<FormInstance>()
const addVisible = ref(false) //添加对话框 显示关闭变量
// 验证规则
const addrules = reactive<FormRules>({
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 3, max: 5, message: '长度3到5', trigger: 'blur' }],
})
const form = reactive({
    name: '',
    pid: null,
    picture: '',
})
const handleClose = () => {
    ElMessageBox.confirm('你确定要关闭对话框吗？')
        .then(() => {
            addruleFormRef.value.resetFields()
            form.name = ''
            form.picture = ''
            console.log(mYupload.value);
            form.pid = null
            mYupload.value!.clearFiles()
            addVisible.value = false
        })
        .catch(() => {
            // catch error
        })
}

const handleCancle = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    form.name = ''
    form.pid = null
    form.picture = ''
    mYupload.value!.clearFiles()
    addVisible.value = false
}

// 上传
const mYupload = ref()
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response, uploadFile);
    form.picture = response.path
}
const handleAvatarSuccess1: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    Editform.dist.picture = response.path

}
// 添加事件
const onSubmit = async (formEl: FormInstance) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if (form.pid instanceof Array) {
                form.pid = form.pid.at(-1)
            }
            let data: any = await service.post('/api/classify/classfiy/', { name: form.name, pid: form.pid, picture: form.picture })
            if (data.code == 200) {
                console.log(data);
                ElMessage({
                    message: '添加成功',
                    type: 'success',
                })
                console.log(mYupload.value);
                form.picture = ''
                mYupload.value!.clearFiles()
                form.name = '',
                    form.pid = null
                addVisible.value = false
                getData()

            } else {
                ElMessage.error('添加失败 亲')
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}


/**
 * 表格
 * */
const xTree1 = ref<VxeTableInstance>()
interface User {
    date: string
    name: string
    address: string,
    picture: string,
    level: string,
    id: string,
    children: Array
}
// 修改
const Editform1 = ref<FormInstance>()
// 验证规则
const editrules = reactive<FormRules>({
    dist: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 3, max: 5, message: '长度3到5', trigger: 'blur' }]
    }
})
const EditFromimg = ref()
const editVisible = ref(false)
let Editform = reactive({
    dist: {
        picture: '',
        name: '',
        id: '',
        pid: 0,
        children: []
    }
})
// 结构对象
const { dist } = toRefs(Editform)
// 修改对话框关闭
const handleEditClose = () => {
    ElMessageBox.confirm('你确定要关闭对话框吗？')
        .then(() => {
            Editform.dist = {
                picture: '',
                name: '',
                id: '',
                pid: 0,
                children: []
            }
            EditFromimg.value.clearFiles()
            editVisible.value = false
        })
        .catch(() => {
            // catch error
        })
}
// 打开修改对话框
const handleEdit = (row: User) => {
    Editform.dist = { ...row }
    editVisible.value = true
}
const reset = () => {
    editVisible.value = false
    Editform1.value?.resetFields()
}
// 确认修改
const onEdit = async (formEl: FormInstance) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if (dist.value.pid instanceof Array) {
                dist.value.pid = dist.value.pid.at(-1)
            }
            delete dist.value.children
            delete dist.value._X_ROW_CHILD
            delete dist.value._X_ROW_KEY
            let data: any = await service.post('/api/classify/editclassfiy/', dist.value)
            if (data.code == 200) {
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
                EditFromimg.value.clearFiles()
                getData()
                editVisible.value = false
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 批量删除
const plDel = () => {
    tableData.dellist.forEach(async (item: any, index: any) => {
        let data = await service.delete('/api/classify/classfiy/?id=' + item.id)
        getData()
    });
    if (tableData.dellist.length != 0) {
        ElMessage({
            type: 'success',
            message: '删除成功',
        })
    }

}
// 删除
const handleDelete = (row: User) => {
    ElMessageBox.confirm(
        '即将删除,确认操作？',
        'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }
    )
        .then(async () => {
            let data: any = await service.delete('/api/classify/classfiy/?id=' + row)
            if (data.code == 200) {
                getData()
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
const selectChangeEvent: VxeTableEvents.CheckboxChange = ({ $table }) => {
    const records = $table.getCheckboxRecords()
    console.info(`勾选${records.length}个树形节点`, records)
    tableData.dellist = records
}
// 获取数据
const tableData = reactive({
    list1: [],
    imgList: [],
    tableTreeConfig: {
        transform: true,
        rowField: 'id',
        parentField: 'pid',
        // vxe-icon-square-plus
        iconOpen: 'vxe-icon-square-minus',
        iconClose: 'vxe-icon-square-plus',
    } as VxeTablePropTypes.TreeConfig,
    option: [] as [],
    dellist: [] as any
})
const getData = async () => {
    let res = await axios.get('/dev-api/api/classify/classfiy/?page=' + pagination.currentPage + '&size=' + pagination.pageSize)
    if (res.data.code == 200) {
        console.log(res);
        tableData.list1 = res.data.data
        tableData.option = res.data.data
        pagination.total = res.data.total
    }
    const flatten = (arr: any) => {
        let result = [] as any;
        for (let i = 0; i < arr.length; i++) {
            result.push(arr[i]);
            if (arr[i].children.length > 0) {
                result = result.concat(flatten(arr[i].children));
                tableData.list1 = result
            }
        }
        return result;
    };
    const a = flatten(res.data.data)
}
onMounted(() => {
    getData()
})
</script>

<style scoped lang="scss">
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .box-card {
        width: 100%;
        height: 100%;
    }
}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

.btn1 {
    margin-bottom: 15px;
}

.el-pagination {
    margin-top: 2%;
    justify-content: flex-end !important;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    font-weight: bold;
}

.demo-image__error .image-slot {
    font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
    font-size: 30px;
}

.demo-image__error .el-image {
    width: 100%;
    height: 200px;
}
</style>